package com.aaa.sso.service;

import com.aaa.entity.Menu;
import com.aaa.entity.User;
import com.aaa.sso.feign.MenuFeign;
import com.aaa.sso.feign.UserFeign;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserDetailsService implements UserDetailsService {

    //sso只负责认证，不负责操作数据库
    //有业务微服务操作数据库 sso只需要从其他模块中调用即可
    //远程调用

    @Resource
    private UserFeign userFeign;
    @Resource
    private MenuFeign menuFeign;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userFeign.getByUsername(s);
        if(user==null){
            throw new RuntimeException("用户不存在");
        }
        //查询用户所具有的权限
        List<Menu> menuList = menuFeign.findByUserid(user.getUserId());
        List<SimpleGrantedAuthority> authorities = menuList.stream().map(item -> new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());

        return new org.springframework.security.core.userdetails.User(user.getPhone(),user.getPassword(),authorities);
    }
}
